package music

import (
	"dustbe/database"
	"dustbe/util"
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type ModifyPackage struct {
	StaffId int `json:"staffId"`
	AlphaTex string `json:"alphaTex"`
	ImgUrl string `json:"imgUrl"`
	Config AlphaTexConfig `json:"config"`
}

func ModifyStaff(c *gin.Context) {
	ok := util.LimitIpInterval(c, 5)
	if !ok {
		c.JSON(http.StatusOK, gin.H{"code" : 4001, "data" : "修改过于频繁"})
		return
	}

	var modifyPackage ModifyPackage
	if c.ShouldBindJSON(&modifyPackage) != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "请求体格式错误"})
		return
	}

	staffId := modifyPackage.StaffId
	alphaTex := strings.TrimSpace(modifyPackage.AlphaTex)
	config := modifyPackage.Config
	imgUrl := modifyPackage.ImgUrl

	if len(alphaTex) == 0 {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "修改的alphaTex不能为空！"})
		return
	}

	user, err := database.FindStaffPublisherByStaffId(staffId)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}


	publisherId := int(user.Id)
	err = checkPrivilegeByPublisherId(c, publisherId)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": err.Error()})
		return
	}

	err = database.ModifyStaff(int64(staffId), config.Title, imgUrl)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "修改数据库失败"})
		return
	}

	staffPath := fmt.Sprintf("%s/%d-%d.json", staffRoot, publisherId, staffId)

	exportAlphaTex := ExportAlphaTex{
		PublisherId: publisherId,
		StaffId: int(staffId),
		AlphaTex: alphaTex,
		Config: config,
		ImgUrl: imgUrl,
	}

	err = util.WriteJson(staffPath, exportAlphaTex)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"code": 4001, "data": "修改写入本地时出错"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"code" : 200, "data" : "发布成功"})
}